/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.msu.config.database;

import io.iec.edp.caf.msu.api.MsuService;
import io.iec.edp.caf.msu.api.ServiceUnitAwareService;
import io.iec.edp.caf.msu.api.client.ServiceDiscovery;
import io.iec.edp.caf.msu.api.client.ServiceRegistry;
import io.iec.edp.caf.msu.client.discovery.DbDiscoveryImpl;
import io.iec.edp.caf.msu.client.health.DbHealthSetting;
import io.iec.edp.caf.msu.client.register.DbRegisterImpl;
import io.iec.edp.caf.msu.common.DBMsuServiceImpl;
import io.iec.edp.caf.msu.common.domain.repository.AppServerRepository;
import io.iec.edp.caf.msu.common.domain.repository.SuRepository;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**
 * @author manwenxing01
 */
@EnableConfigurationProperties(DbHealthSetting.class)
@EnableJpaRepositories({"io.iec.edp.caf.msu.common.domain.repository"})
@EntityScan({"io.iec.edp.caf.msu.common.domain.entity"})
@AutoConfigureBefore(name = {"io.iec.edp.caf.msu.config.MsuServiceAutoConfiguration"})
@Configuration(proxyBeanMethods = false)
public class MsuDatabaseAutoConfiguration {

    @Bean
    @ConditionalOnExpression("'${msu.deployMode}'!='Custom' && !${msu.enable}")
    public ServiceRegistry serviceRegister(ServiceUnitAwareService suAware, AppServerRepository appRepo, SuRepository suRepo) {
        return new DbRegisterImpl(appRepo, suRepo, suAware);
    }

    @Bean
    @ConditionalOnExpression("'${msu.deployMode}'!='Custom' && !${msu.enable}")
    public ServiceDiscovery serviceDiscovery(AppServerRepository appRepo, SuRepository suRepo) {
        return new DbDiscoveryImpl(appRepo, suRepo);
    }

    @Bean
    @ConditionalOnExpression("'${msu.deployMode}'!='Custom' && !${msu.enable}")
    public MsuService createMSUService(ServiceUnitAwareService suAware, ServiceDiscovery serviceDiscovery, AppServerRepository appRepo, SuRepository suRepo) {
        return new DBMsuServiceImpl(suAware, serviceDiscovery, appRepo, suRepo);
    }

}
